package com.kk.base.service.home;

import com.kk.base.bean.PageBean;
import com.kk.base.dao.admin.UserDao;
import com.kk.base.dao.home.BranchApplyForDao;
import com.kk.base.entity.admin.Role;
import com.kk.base.entity.admin.User;
import com.kk.base.entity.admin.UserRoleTypeEnum;
import com.kk.base.entity.home.BranchApplyFor;
import com.kk.base.entity.home.BranchApplyForStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @info 网点申请业务处理层
 */
@Service
public class BranchApplyForService {

    @Autowired
    private BranchApplyForDao branchApplyForDao;
    @Autowired
    private UserDao userDao;

    /**
     * 根据网点申请id查询
     * @param id
     * @return
     */
    public BranchApplyFor find(Long id){
        return branchApplyForDao.find(id);
    }

    /**
     * 通过申请人查询
     * @param homeUserId
     * @return
     */
    public List<BranchApplyFor> findByHomeUser_Id(Long homeUserId){
        return branchApplyForDao.findByHomeUser_Id(homeUserId);
    }

    /**
     * 根据前台用户和申请状态查询
     * @param homeUserId
     * @param branchApplyForStatus
     * @return
     */
    public BranchApplyFor findByHomeUser_IdAndBranchApplyForStatus(Long homeUserId, BranchApplyForStatusEnum branchApplyForStatus){
        return branchApplyForDao.findByHomeUser_IdAndBranchApplyForStatus(homeUserId,branchApplyForStatus);
    }

    /**
     * 网点申请添加/编辑操作
     * @param branchApplyFor
     * @return
     */
    public BranchApplyFor save(BranchApplyFor branchApplyFor){
        return branchApplyForDao.save(branchApplyFor);
    }


    /**
     * 通过申请
     * @param id
     * @param role
     * @return
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRES_NEW, timeout = 15)
    public Integer agreeBranchApplyFor(Long id,Role role) {
        Integer agreeStatus = 0;
        try {
            BranchApplyFor branchApplyFor = branchApplyForDao.find(id);
            branchApplyFor.setBranchApplyForStatus(BranchApplyForStatusEnum.THROUGH);
            User user = new User();
            user.setUsername(branchApplyFor.getBranchName());
            user.setPassword("123456");
            user.setUserType(UserRoleTypeEnum.BRANCHES);
            user.setMobile(branchApplyFor.getMobile());
            user.setAddress(branchApplyFor.getAddress());
            user.setOfficeAddress(branchApplyFor.getOfficeAddress());
            user.setBranchType(branchApplyFor.getBranchType());
            user.setRole(role);
            user.setIdCard(branchApplyFor.getIdCard());
            user.setLongitudeAndIatitude(branchApplyFor.getLongitudeAndIatitude());
            userDao.save(user);
            branchApplyForDao.save(branchApplyFor);
        } catch (Exception e) {
            agreeStatus = 1;
        }
        return agreeStatus;
    }


    /**
     * 分页查询网点申请列表
     * @param branchName
     * @param pageBean
     * @return
     */
    public PageBean<BranchApplyFor> findList(PageBean<BranchApplyFor> pageBean, String branchName,Long homeUserId) {
        Specification<BranchApplyFor> specification = new Specification<BranchApplyFor>() {
            @Override
            public Predicate toPredicate(Root<BranchApplyFor> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates  = new ArrayList<>();
                if (branchName != null){
                    Predicate predicate1 = criteriaBuilder.like(root.get("branchName"), "%" + branchName + "%");
                    predicates.add(predicate1);
                }
                if (homeUserId != null){
                    Predicate predicate2 = criteriaBuilder.equal(root.get("homeUser"), homeUserId);
                    predicates.add(predicate2);
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createTime")));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<BranchApplyFor> findAll = branchApplyForDao.findAll(specification,pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }

    /**
     * 判断网点申请名是否存在，添加和编辑均可判断
     * @param branchName
     * @param id
     * @return
     */
    public boolean isExistBranchName(String branchName,Long id){
        BranchApplyFor branchApplyFor = branchApplyForDao.findByBranchName(branchName);
        if(branchApplyFor != null){
            //表示网点申请名存在，接下来判断是否是编辑网点申请的本身
            if(branchApplyFor.getId().longValue() != id.longValue()){
                return true;
            }
        }
        return false;
    }

    /**
     * 按照网点申请id删除
     * @param id
     */
    public void delete(Long id){
        branchApplyForDao.deleteById(id);
    }

    /**
     * 返回网点申请总数
     * @return
     */
    public long total(){
        return branchApplyForDao.count();
    }
    
    

}
